package org.finesys.system.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.finesys.common.constants.CacheConstants;
import org.finesys.common.core.constants.enums.DictTypeEnum;
import org.finesys.common.core.exception.ErrorCodes;
import org.finesys.common.core.util.MessageUtil;
import org.finesys.common.mp.core.service.impl.BaseServiceImpl;
import org.finesys.system.api.entity.SysDict;
import org.finesys.system.api.entity.SysDictItem;
import org.finesys.system.mapper.SysDictItemMapper;
import org.finesys.system.service.SysDictItemService;
import org.finesys.system.service.SysDictService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class SysDictItemServiceImpl extends BaseServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {

    private final SysDictService sysDictService;

    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
    public Boolean removeDictItem(Long id) {
        //根据ID查询字典ID
        SysDictItem sysDictItem = this.getById(id);
        SysDict sysDict = sysDictService.getById(sysDictItem.getDictId());
        //系统内置
        Assert.state(!DictTypeEnum.SYSTEM.getType().equals(sysDict.getSystemFlag()), MessageUtil.getMessage(ErrorCodes.SYS_DICT_DELETE_SYSTEM));
        this.removeById(id);
        return Boolean.TRUE;
    }

    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
    public Boolean removeDictItems(Long[] ids) {
        //根据ID查询字典ID
        Optional.ofNullable(ids).ifPresent(items -> {
            Arrays.stream(items).forEach(itemId -> removeDictItem(itemId));
        });
        return Boolean.TRUE;
    }

    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#item.dictType")
    public Boolean updateDictItem(SysDictItem item) {
        //根据ID查询字典ID
        SysDictItem sysDictItem = this.getById(item.getId());
        SysDict sysDict = sysDictService.getById(sysDictItem.getDictId());
        //系统内置
        Assert.state(!DictTypeEnum.SYSTEM.getType().equals(sysDict.getSystemFlag()), MessageUtil.getMessage(ErrorCodes.SYS_DICT_UPDATE_SYSTEM));
        this.updateById(item);
        return Boolean.TRUE;
    }

    @Override
    @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type", unless = "#result.isEmpty()")
    public List<SysDictItem> findType(String type) {
        return baseMapper.selectList(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getDictType, type));
    }
}
